<?php
namespace App\Utils\Logic\Ly;
use App\Utils\Adapter\Map;
use App\Utils\Service\Ly\EsServer;
use App\Utils\Thirdparty\Map\Amap;

class FangSearchLogic
{
    public static function searchHouse($address,$region)
    {

        $amapAdapter = new Map(new Amap());
        //目的地
        $start = $amapAdapter->getLocation($address);
       list( $lon,$lat) = explode(',',$start);


        //设置条件
      //  if(!empty($keyword)) $wheres[]= ['match'=>['region'=>$region]];
        $wheres =   [
            'geo_distance' => [ // 根据位置距离过滤结果
                'distance' => '15km', // 距离限制在 10 公里以内
                'address' => [ 'lat' => $lat, 'lon' => $lon], // 用户传递的位置信息
            ]
        ];
        //房源搜索,用排序
        //房源搜索,用排序
        $sort=[
            '_geo_distance' => [
                'address' => [ 'lat' =>$lat, 'lon' => $lon],
                'order' => 'asc',
                'unit' => 'km',
                'distance_type' => 'plane'
            ]
        ];;

        //发送查询请求并获取结果
        $response = EsServer::EsIndex()->search('ly_fang',$wheres,$sort);

        dd($response);
        $data=[];
        $test=[];
        foreach ($response['hits']['hits'] as $item=> $value){
               foreach ($value['_source'] as $i => $v){
                $data[$i]=$v;
               }
            $test[]= $data;

        }
        return $test;

        if(empty($response['hits']['hits'])) throw new \Exception('附近没有房源');
//        foreach ($response['hits']['hits'] as $key => $hit) {
//            $house = $hit['_source'];
//            $distance = round($hit['sort'][0],3)."km"; // 房源与用户传递的位置的距离，单位为km 保留三位小数
//            $data[$key]['house']['fang_title']= $house['fang_title'];
//            $data[$key]['house']['address']= $house['address'];
//            $data[$key]['distance'] = $distance;
//        }
        return $data;
    }
}
